//
//  AppDelegate.m
//  TryShopping
//
//  Created by LiYinDi on 16/6/2.
//  Copyright © 2016年 RuiBen. All rights reserved.
//

#import "AppDelegate.h"
#import <AlipaySDK/AlipaySDK.h>
//#import "RDVTabBarController.h"
#import "RDVTabBarItem.h"
#import "ExhibitionViewController.h"
#import "DiscoverHouseholdListViewController.h"
#import "MyViewController.h"
#import "UMSocial.h"
#import "CashierNewViewController.h"
#import "UMSocialWechatHandler.h"
//#import "PrinterSDK.h"
//#import "SVProgressHUD.h"
//#import <PgyUpdate/PgyUpdateManager.h>
#import "JPUSHService.h"
#import <AdSupport/AdSupport.h>
#import <UserNotifications/UserNotifications.h>


#import "OrderDetailViewController.h"
#import "OrderDeliveryDetailViewController.h"
#import "CheckVouchDetailViewController.h"
#import "WhsOutAddWhsInDetailViewController.h"
#import "BookingOrderDetailViewController.h"
#import "GoodsInOrderDetailViewController.h"
#import "AllotOrderDetailViewController.h"
#import "NeedOrderDetailViewController.h"

static NSString *channel = @"Publish channel";
static BOOL isProduction = FALSE;
@interface AppDelegate ()<JPUSHRegisterDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    [self setupViewControllers];
    [self.window setRootViewController:self.viewController];
    [self.window makeKeyAndVisible];
    
    [[UINavigationBar appearance] setBarTintColor:[UIColor whiteColor]];
    [self customizeInterface];
   
    //  [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
    //  [application setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
    [[UITextField appearance] setTintColor:luseColor];
    //     [[UILabel appearance] setFont:[UIFont fontWithName:@"STHeitiSC-Light" size:14]];
    //  [[UINavigationBar appearance] setTintColor:[UIColor blackColor]];
    
  
    CGSize viewSize = self.window.bounds.size;
    
    NSString *viewOrientation = @"Portrait";    //横屏请设置成 @"Landscape"
    
    NSString *launchImage = nil;
    
    NSArray* imagesDict = [[[NSBundle mainBundle] infoDictionary] valueForKey:@"UILaunchImages"];
    
    for (NSDictionary* dict in imagesDict)
        
    {
        
        CGSize imageSize = CGSizeFromString(dict[@"UILaunchImageSize"]);
        
        
        
        if (CGSizeEqualToSize(imageSize, viewSize) && [viewOrientation isEqualToString:dict[@"UILaunchImageOrientation"]])
            
        {
            
            launchImage = dict[@"UILaunchImageName"];
            
        }
        
    }
    
    UIImageView *launchView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"launchimage"]];
    
    launchView.frame = self.window.bounds;
    
    launchView.contentMode = UIViewContentModeScaleAspectFill;
    
    [self.window addSubview:launchView];
    
    [UIView animateWithDuration:1.0f
     
                          delay:0.5f
     
                        options:UIViewAnimationOptionBeginFromCurrentState
     
                     animations:^{
                         
                         
                         
                         launchView.alpha = 0.0f;
                         
                         launchView.layer.transform = CATransform3DScale(CATransform3DIdentity, 1.2, 1.2, 1);
                         
                         
                         
                     }
     
                     completion:^(BOOL finished) {
                         
                         
                         
                         [launchView removeFromSuperview];
                         
                         
                         
                     }];
    
    
    
    
    
    
    
    [UMSocialData setAppKey:@"564c046767e58eba1300118e"];
    [[UIApplication sharedApplication]
     canOpenURL:[NSURL URLWithString:@"weixin(微信)://"]];
    NSString *str1=[NSString stringWithFormat:@"%d",TARGET_VERSION];
    NSString *plistPath1 = [[NSBundle mainBundle] pathForResource:str1 ofType:@"plist"];
    NSDictionary *dictionary1 = [[NSDictionary alloc] initWithContentsOfFile:plistPath1];
    NSString *setWXAppId = [dictionary1 objectForKey:@"setWXAppId"];
    NSString *appSecret = [dictionary1 objectForKey:@"appSecret"];
    NSString *appKey = [dictionary1 objectForKey:@"appKey"];
//    NSLog(@"rongYunKey^^^^^===%@",setWXAppId);

    [UMSocialWechatHandler setWXAppId:setWXAppId appSecret:appSecret url:@"http://www.honglinkTech.com"];
  
    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
        JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
        entity.types = UNAuthorizationOptionAlert|UNAuthorizationOptionBadge|UNAuthorizationOptionSound;
        [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];

    } else if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    } else {
        //categories 必须为nil
        [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                          UIRemoteNotificationTypeSound |
                                                          UIRemoteNotificationTypeAlert)
                                              categories:nil];
    }
    
    
    

    //如不需要使用IDFA，advertisingIdentifier 可为nil
    [JPUSHService setupWithOption:launchOptions appKey:appKey
                          channel:channel
                 apsForProduction:isProduction
            advertisingIdentifier:advertisingId];
   

    //2.1.9版本新增获取registration id block接口。
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0){
            NSLog(@"registrationID获取成功：%@",registrationID);
            NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
            [user setObject:registrationID forKey:@"jpushRegId"];
            [user synchronize];
        }
        else{
            NSLog(@"registrationID获取失败，code：%d",resCode);
        }
    }];
   
    
    return YES;

}

- (void)setupViewControllers {
    
    //
    UIViewController *secondViewController = [[MyViewController alloc] init];
    UIViewController *MyNavigationController = [[UINavigationController alloc]
                                                initWithRootViewController:secondViewController];
    //
    UIViewController *thirdViewController = [[DiscoverHouseholdListViewController alloc] init];
    UIViewController *DiscoverNavigationController = [[UINavigationController alloc]
                                                      initWithRootViewController:thirdViewController];

    
    
    CashierNewViewController *scanVC = [[CashierNewViewController alloc] init];
    UIViewController *centerNavigationController11 = [[UINavigationController alloc]
                                                      initWithRootViewController:scanVC];
    
    ExhibitionViewController *ViViewController = [[ExhibitionViewController alloc] init];
    ViViewController.titleStr=@"橱窗";
    ViViewController.isHidden=NO;
    UIViewController *ServiceNavigationController = [[UINavigationController alloc]
                                                     initWithRootViewController:ViViewController];
    

    NSString *str1=[NSString stringWithFormat:@"%d",TARGET_VERSION];
//     NSLog(@"str1111===%@",str1);
    NSString *plistPath1 = [[NSBundle mainBundle] pathForResource:str1
                                                          ofType:@"plist"];
    NSDictionary *dictionary1 = [[NSDictionary alloc] initWithContentsOfFile:plistPath1];
//    NSLog(@"dictionary1===%@",dictionary1);
    NSString *URLString1 = [dictionary1 objectForKey:@"Home"];
    UIViewController * vc1 = (UIViewController*)[[NSClassFromString(URLString1) alloc] init];
//    NSLog(@"URLString1111===%@",URLString1);
    UIViewController *RDNavigationController111 = [[UINavigationController alloc]
                                                  initWithRootViewController:vc1];
    
    
    RDVTabBarController *tabBarController = [[RDVTabBarController alloc] init];
    [tabBarController setViewControllers:@[RDNavigationController111,ServiceNavigationController,centerNavigationController11,DiscoverNavigationController,MyNavigationController]];
    self.viewController = tabBarController;
    [self customizeTabBarForController:tabBarController];
}

- (void)customizeTabBarForController:(RDVTabBarController *)tabBarController {
    NSArray *tabBarItemImages = @[@"shouye",@"zhanting",@"saoyisao",@"faxian",@"wode"];
    
    NSInteger index = 0;
    for (RDVTabBarItem *item in [[tabBarController tabBar] items]) {
        
        UIImage *selectedimage = [UIImage imageNamed:[NSString stringWithFormat:@"%@_hight",
                                                      [tabBarItemImages objectAtIndex:index]]];
        UIImage *unselectedimage = [UIImage imageNamed:[NSString stringWithFormat:@"%@_normal",
                                                        [tabBarItemImages objectAtIndex:index]]];
        [item setFinishedSelectedImage:selectedimage withFinishedUnselectedImage:unselectedimage];
        
        index++;
    }
}
- (void)customizeInterface {
    UINavigationBar *navigationBarAppearance = [UINavigationBar appearance];
    
    UIImage *backgroundImage =nil;
    NSDictionary *textAttributes = nil;
    
    if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_6_1) {
        backgroundImage = nil;
        textAttributes = @{
                           NSFontAttributeName: [UIFont boldSystemFontOfSize:16],
                           NSForegroundColorAttributeName: [UIColor blackColor],
                           };
        
        
    } else {
#if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_7_0
        backgroundImage =nil;
        
        textAttributes = @{
                           UITextAttributeFont: [UIFont boldSystemFontOfSize:16],
                           UITextAttributeTextColor: [UIColor blackColor],
                           UITextAttributeTextShadowColor: [UIColor clearColor],
                           UITextAttributeTextShadowOffset: [NSValue valueWithUIOffset:UIOffsetZero],
                           };
#endif
    }
    
    [navigationBarAppearance setBackgroundImage:backgroundImage
                                  forBarMetrics:UIBarMetricsDefault];
    [navigationBarAppearance setTitleTextAttributes:textAttributes];
}
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return  [UMSocialSnsService handleOpenURL:url];
}
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
    return  [UMSocialSnsService handleOpenURL:url];
}


-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{


}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    NSUserDefaults*pushJudge = [NSUserDefaults standardUserDefaults];
    [pushJudge removeObjectForKey:@"pushUserInfo"];
    [pushJudge synchronize];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.

    [application setApplicationIconBadgeNumber:0];   //清除角标
    [application cancelAllLocalNotifications];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    [[NSNotificationCenter defaultCenter]postNotificationName:@"NewVersion" object:nil];
   
    NSUserDefaults*pushJudge = [NSUserDefaults standardUserDefaults];
    NSDictionary*userInfo=[pushJudge objectForKey:@"pushUserInfo"];
    if (userInfo.count==0) {
    }else{
    application.applicationIconBadgeNumber = 0;
    [self goToMssageViewControllerWith:userInfo];
    }
    
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.

}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "RuiBen.TryShopping" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"TryShopping" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    // Create the coordinator and store
    
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"TryShopping.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}


- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}


- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:
(void (^)(UIBackgroundFetchResult))completionHandler {
    [JPUSHService handleRemoteNotification:userInfo];
    NSLog(@"iOS7及以上系统，收到通知:%@",
    [self logDic:userInfo]);
    NSUserDefaults*pushJudge = [NSUserDefaults standardUserDefaults];
    [pushJudge setObject:userInfo forKey:@"pushUserInfo"];
    [pushJudge synchronize];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"userInfo" object:nil];
    completionHandler(UIBackgroundFetchResultNewData);
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    /// Required -    DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];


}
- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
    
    
    
//    [JPUSHService showLocalNotificationAtFront:notification identifierKey:nil];
}
- (void)goToMssageViewControllerWith:(NSDictionary*)msgDic{
    //将字段存入本地，因为要在你要跳转的页面用它来判断,这里我只介绍跳转一个页面，
    NSUserDefaults*pushJudge = [NSUserDefaults standardUserDefaults];
    [pushJudge setObject:@"push"forKey:@"push"];
    [pushJudge removeObjectForKey:@"pushUserInfo"];
    [pushJudge synchronize];
    NSString * taskType = [msgDic objectForKey:@"taskType"];
    NSString * orderId = [msgDic objectForKey:@"orderId"];
    if ([taskType isEqualToString:@"DOrder_NA"]||[taskType isEqualToString:@"DOrder_ND"]) {
           OrderDetailViewController * VC = [[OrderDetailViewController alloc]init];
           VC.orderId=orderId;
           UINavigationController * Nav = [[UINavigationController alloc]initWithRootViewController:VC];//这里加导航栏是因为我跳转的页面带导航栏，如果跳转的页面不带导航，那这句话请省去。
           [self.window.rootViewController presentViewController:Nav animated:YES completion:nil];
    }else if ([taskType isEqualToString:@"DBookingOrder_NA"]) {
        
        BookingOrderDetailViewController * VC = [[BookingOrderDetailViewController alloc]init];
        VC.orderId=orderId;
        UINavigationController * Nav = [[UINavigationController alloc]initWithRootViewController:VC];//这里加导航栏是因为我跳转的页面带导航栏，如果跳转的页面不带导航，那这句话请省去。
        [self.window.rootViewController presentViewController:Nav animated:YES completion:nil];

        
    }else if ([taskType isEqualToString:@"DNeedOrder_Results"]) {
        NeedOrderDetailViewController * VC = [[NeedOrderDetailViewController alloc]init];
        VC.orderId=orderId;
        UINavigationController * Nav = [[UINavigationController alloc]initWithRootViewController:VC];//这里加导航栏是因为我跳转的页面带导航栏，如果跳转的页面不带导航，那这句话请省去。
        [self.window.rootViewController presentViewController:Nav animated:YES completion:nil];

        
        
    }else if ([taskType isEqualToString:@"DAllotOrder_NA"]||[taskType isEqualToString:@"DAllotOrder_YO"]||[taskType isEqualToString:@"DAllotOrder_Results"]) {
        AllotOrderDetailViewController * VC = [[AllotOrderDetailViewController alloc]init];
        VC.orderId=orderId;
        UINavigationController * Nav = [[UINavigationController alloc]initWithRootViewController:VC];//这里加导航栏是因为我跳转的页面带导航栏，如果跳转的页面不带导航，那这句话请省去。
        [self.window.rootViewController presentViewController:Nav animated:YES completion:nil];

    }else if ([taskType isEqualToString:@"DGoodsInOrder_YO"]) {
        GoodsInOrderDetailViewController * VC = [[GoodsInOrderDetailViewController alloc]init];
        VC.orderId=orderId;
        UINavigationController * Nav = [[UINavigationController alloc]initWithRootViewController:VC];//这里加导航栏是因为我跳转的页面带导航栏，如果跳转的页面不带导航，那这句话请省去。
        [self.window.rootViewController presentViewController:Nav animated:YES completion:nil];

        
    }else if ([taskType isEqualToString:@"DCheckVouch_NP"]) {
        CheckVouchDetailViewController * VC = [[CheckVouchDetailViewController alloc]init];
        VC.orderId=orderId;
        UINavigationController * Nav = [[UINavigationController alloc]initWithRootViewController:VC];//这里加导航栏是因为我跳转的页面带导航栏，如果跳转的页面不带导航，那这句话请省去。
        [self.window.rootViewController presentViewController:Nav animated:YES completion:nil];

        
    }
}



//#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#pragma mark- JPUSHRegisterDelegate
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {

    NSDictionary * userInfo = response.notification.request.content.userInfo;
    UNNotificationRequest *request = response.notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容

    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题

    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
       [JPUSHService handleRemoteNotification:userInfo];
        NSLog(@"iOS10 收到远程通知:%@", [self logDic:userInfo]);
        //[rootViewController addNotificationCount];

    }
    else {
       // 判断为本地通知
       NSLog(@"iOS10 收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
    }

    completionHandler();  // 系统要求执行这个方法
}

// log NSSet with UTF8
// if not ,log will be \Uxxx
- (NSString *)logDic:(NSDictionary *)dic {
    if (![dic count]) {
        return nil;
    }
    NSString *tempStr1 =
    [[dic description] stringByReplacingOccurrencesOfString:@"\\u"
                                                 withString:@"\\U"];
    NSString *tempStr2 =
    [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 =
    [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString *str =
    [NSPropertyListSerialization propertyListFromData:tempData
                                     mutabilityOption:NSPropertyListImmutable
                                               format:NULL
                                     errorDescription:NULL];
    return str;
}

@end
